﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPOI.HSSF;
using NPOI.POIFS;
using NPOI.SS;
using NPOI.Util;
using NPOI.Util.Collections;
using NPOI.DDF;
using NPOI.HPSF;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;

namespace TaxesImport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void BtnPersonImportClick(object sender, EventArgs e)
        {
            if (tbUser.Text.Trim() == string.Empty)
            {
                MessageBox.Show(@"请选择文件!", @"提示", MessageBoxButtons.OK);
                return;
            }
            var backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += BackgroundWorkerDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
            backgroundWorker.ProgressChanged += BackgroundWorkerProgressChanged;
            backgroundWorker.RunWorkerAsync(backgroundWorker);
        }

        void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.btnPersonImport.Enabled = true;
        }

        void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btnPersonImport.Enabled = true;
        }

         void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
         {
             var work = e.Argument as BackgroundWorker;

             var fileName = tbUser.Text.Trim();
             var users = new List<User>();

             #region 解析excel

             using (var stream = new FileStream(fileName,FileMode.Open,FileAccess.Read))
             {
                 var workBook = new HSSFWorkbook(stream);
                    var enumerator =  workBook.GetEnumerator();
                 while (enumerator.MoveNext())
                 {
                     var sheet = (HSSFSheet) enumerator.Current;
                     if (sheet == null) continue;
                     var rowEnumerator = sheet.GetEnumerator();
                     while(rowEnumerator.MoveNext())
                     {
                         var row = (HSSFRow) rowEnumerator.Current;
                         if (row == null)
                             break;
                         var firstCell = (HSSFCell) row.GetCell(0);
                         if(firstCell==null) break;
                         if(firstCell.StringCellValue=="用户名")continue;
                         var user = new User();
                         var cellEnumerator = row.GetEnumerator();
                         while (cellEnumerator.MoveNext())
                         {

                             var cell = cellEnumerator.Current as HSSFCell;
                             if (cell == null) continue;
                             switch (cell.ColumnIndex)
                             {
                                 case 0:
                                     user.LoginName = cell.StringCellValue;
                                     break;
                                 case 1:
                                     user.Department = cell.StringCellValue;
                                     break;
                                 case 2:
                                     user.Name = cell.StringCellValue;
                                     break;
                                 case 3:
                                     var value = cell.StringCellValue;
                                     user.IsSupper = value.Trim() == "管理员";
                                     break;
                             }
                         }
                         users.Add(user);
                     }
                 }
             }

             #endregion

             //根据Users来进行插入数据库操作。并上报进度

             for (var i = 0; i < users.Count; i++)
             {
                 users[i].Insert();
                 if(work!=null)
                     work.ReportProgress((int)(((float)i/users.Count)*100));
             }
         }

        private void BtnUserBrowseClick(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog()
                          {
                              Filter = @"Excel Files (.xls)|*.xls",
                              Multiselect = false
                          };
            if(dlg.ShowDialog()!= DialogResult.OK)
                return;
            tbUser.Text = dlg.FileName;
        }

        private void BtnTradeBrowseClick(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog()
            {
                Filter = @"Excel Files (.xls)|*.xls",
                Multiselect = false
            };
            if (dlg.ShowDialog() != DialogResult.OK)
                return;
            tbTrade.Text = dlg.FileName;
        }

        private void BtnTradeImportClick(object sender, EventArgs e)
        {
            if (tbTrade.Text.Trim() == string.Empty)
            {
                MessageBox.Show(@"请选择文件!", @"提示", MessageBoxButtons.OK);
                return;
            }
            var tradeBackgroundWorker = new BackgroundWorker();
            tradeBackgroundWorker.DoWork += TradeBackgroundWorkerDoWork;
            tradeBackgroundWorker.RunWorkerCompleted += TradeBackgroundWorkerRunWorkerCompleted;
            tradeBackgroundWorker.ProgressChanged += TradeBackgroundWorkerProgressChanged;
            tradeBackgroundWorker.RunWorkerAsync(tradeBackgroundWorker);
        }

        void TradeBackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           
        }

        void TradeBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.tbTrade.Text = string.Empty;
        }

        void TradeBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var work = e.Argument as BackgroundWorker;

            var fileName = tbTrade.Text.Trim();
            var bigTrades = new List<BigTrade>();

            #region 解析excel

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                var workBook = new HSSFWorkbook(stream);

                var sheetEnumerator = workBook.GetEnumerator();
                while (sheetEnumerator.MoveNext())
                {
                    var sheet = sheetEnumerator.Current as HSSFSheet;
                    if(sheet ==null)
                        continue;
                    var rowEnumerator = sheet.GetEnumerator();
                    BigTrade bigTrade = null;
                    Trade trade = null;
                    while (rowEnumerator.MoveNext())
                    {
                        var row = rowEnumerator.Current as HSSFRow;
                        if(row==null)
                            continue;
                        //正式内容从第三行开始
                        if (row.RowNum >= 2)
                        {
                            var cellEnumerator = row.GetEnumerator();
                            var isBigTrade = false;
                            while (cellEnumerator.MoveNext())
                            {
                                var cell = cellEnumerator.Current as HSSFCell;
                                if (cell == null)
                                    continue;
                                switch (cell.ColumnIndex)
                                {
                                    case 0:
                                        if (string.IsNullOrEmpty(cell.StringCellValue))
                                        {
                                            trade = new Trade();
                                            isBigTrade = false;
                                        }
                                        else
                                        {
                                            if(bigTrade!=null )
                                            bigTrades.Add(bigTrade);
                                            bigTrade = new BigTrade {TypeCode = cell.StringCellValue};
                                            trade = null;
                                            isBigTrade = true;
                                        }
                                        break;
                                    case 1:
                                        {
                                            if (!isBigTrade)
                                                if (trade != null)
                                                    switch (cell.CellType)
                                                    {
                                                            case CellType.NUMERIC:
                                                            trade.TypeCode = cell.NumericCellValue.ToString();
                                                            break;
                                                        case  CellType.STRING:
                                                            trade.TypeCode = cell.StringCellValue;
                                                            break;
                                                    }
                                                  
                                        }
                                        break;
                                    case 2:
                                        if (isBigTrade)
                                            bigTrade.Name = cell.StringCellValue;
                                        else if (trade != null) trade.Name = cell.StringCellValue;
                                        break;
                                }
                            }
                            if(bigTrade!=null&&trade!=null)
                                bigTrade.Trades.Add(trade);
                        }
                    }
                }
            }


            #endregion
            
            //进库报进度
        }
    }
}
